/*
 * bluetooth.c
 *
 *  Created on: 16 jun. 2011
 *      Author: dirkjan
 */
#include <stdio.h>
#include <stdlib.h>
#include "bluetooth.h"
#include <avr/interrupt.h>

static unsigned char TX_data[send_data_buff_len];
static unsigned char TX_buff_len=0, TX_buff_nr=0;

static volatile unsigned char RX_data_ready=0, RX_data=0;

ISR (USART_RX_vect){
	if (!RX_data_ready){
		RX_data_ready=1;
		RX_data=UDR0;
	}
}

void blue_init(void){
	DDRD|=(1<<PD1);

	/*Set baud rate */
	UBRR0H = (unsigned char)(DEFAULT_UBRR>>8);
	UBRR0L = (unsigned char)DEFAULT_UBRR;

	/*Enable receiver and transmitter and receive interrupt*/
	UCSR0B = (1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0);
	/* Set frame format: 8data, 1stop bit */
	UCSR0C = (3<<UCSZ00);

	bluetooth_send_text("Heli0013\r\n");
}

void blue_task(){
	if (TX_buff_len && (UCSR0A & (1<<UDRE0))){		// is er data om te verzenden? en is de verzend buffer leeg
		UDR0 = TX_data[TX_buff_nr];
		TX_buff_len--;
		TX_buff_nr++;
		if (TX_buff_nr>=send_data_buff_len)
			TX_buff_nr = 0;
	} else if (TX_buff_len==0){
		TX_buff_nr=0;
	}

}

void bluetooth_send_char(unsigned char data){
	unsigned char TX_buff_fill_nr=TX_buff_nr+TX_buff_len;	// plek om de data in te gooien
	if (TX_buff_len<send_data_buff_len){
		if (TX_buff_fill_nr>=send_data_buff_len)
			TX_buff_fill_nr = 0;
		TX_data[TX_buff_fill_nr] = data;
		TX_buff_len++;
	}
}

void bluetooth_send_text (char *t)
{
    while (*t){
    	bluetooth_send_char(*t);
        t++;
    }
}

void bluetooth_send_nr(signed int nummer)
{
	char t[10];
	itoa(nummer,t,10);	// decimale waarde
	bluetooth_send_text(t);
}


unsigned char bluetooth_get_data(void){
	RX_data_ready=0;
	return RX_data;
}

unsigned char bluetooth_data_ready(void){
	return RX_data_ready;
}
